package com.zhupanlin.zhyl.user.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.zhupanlin.zhyl.common.result.Result;
import com.zhupanlin.zhyl.common.utils.JwtHelper;
import com.zhupanlin.zhyl.model.user.UserInfo;
import com.zhupanlin.zhyl.user.service.UserInfoService;
import com.zhupanlin.zhyl.user.utils.ConstantWXPropertiesUtils;
import com.zhupanlin.zhyl.user.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/12/1 20:01
 */
// 微信操作的接口
@Controller
@RequestMapping("/api/ucenter/wx")
public class WXApiController {

    @Autowired
    private UserInfoService userInfoService;

    // 1. 生成微信扫描二维码
    /**
     * 获取微信登录参数
     */
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result genQrConnect() {
        Map<String, Object> map = new HashMap<>();
        try {
            map.put("appid", ConstantWXPropertiesUtils.APP_ID);
            map.put("scope", "snsapi_login");
            String redirectUrl = ConstantWXPropertiesUtils.REDIRECT_URL;
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
            map.put("redirect_uri", redirectUrl);
            map.put("state", System.currentTimeMillis() + "");
            return Result.ok(map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 微信扫码后回调的方法
    @GetMapping("callback")
    public String callback(String code, String state) {
        // 获取临时票据 code
        System.out.println("code = " + code);
        // 拿着 code 和 微信id 和密钥，去请求微信固定地址，
        // 得到 access_token 和
        StringBuffer sb = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");

        String accessTokenUrl = String.format(sb.toString(),
                ConstantWXPropertiesUtils.APP_ID,
                ConstantWXPropertiesUtils.APP_SECRET,
                code);

        // 使用 HttpClients 去请求这个地址
        try {
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenInfo = " + accessTokenInfo);
            // 获取 openid 和 access_token
            JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
            String openid = jsonObject.getString("openid");
            String accessToken = jsonObject.getString("access_token");

            // 判断数据库中是否已经存在
            UserInfo userInfo = userInfoService.selectWxInfoByOpenId(openid);

            if (userInfo == null) {
                // 第三步 拿着 openid 和 access_token 请求微信地址，得到扫码人信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
                String resultInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("resultInfo = " + resultInfo);
                // 解析用户信息
                JSONObject resultInfoObject = JSONObject.parseObject(resultInfo);
                String nickname = resultInfoObject.getString("nickname");
                String headImageUrl = resultInfoObject.getString("headimageurl");

                // 获取扫码人信息添加至数据库
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }



            // 返回 name 和 token 的字符串
            HashMap<String, String> map = new HashMap<>();
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);

            if (StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);
            return "redirect:"
                    + ConstantWXPropertiesUtils.ZHYL_BASE_URL + "/weixin/callback?token="+map.get("token")+"&openid="+map.get("openid")+"&name="+URLEncoder.encode((String)map.get("name"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
